$(function() {
    initArtList()
    let layer = layui.layer

    function initArtList() {
        $.ajax({
            method: 'get',
            url: '/my/cate/list',
            success: function(res) {
                console.log(res);
                let htmlStr = template('tpl-table', res)
                $('tbody').html(htmlStr)
            }
        })
    }
    let indexAdd = null
    $('#btnAddCate').on('click', function() {
        indexAdd = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $('#dialog_add').html()
        });
    })
    $('body').on('submit', '#form_add', function(e) {
        e.preventDefault()
        $.ajax({
            method: 'post',
            url: '/my/cate/add',
            data: $(this).serialize(),
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('新增文章类别失败！')
                }
                initArtList()
                layer.msg('新增文章类别成功！')
                layer.close(indexAdd);
            }
        })
    })
    let indexEdit = null
    let form = layui.form
    $('tbody').on('click', '#btn_edit', function(e) {
        indexEdit = layer.open({
            type: 1,
            area: ['500px', '250px'],
            title: '添加文章分类',
            content: $('#dialog_edit').html()
        });
        let id = $(this).attr('data-id')
        $.ajax({
            method: 'get',
            url: '/my/cate/info?id=' + id,
            success: function(res) {
                console.log(res);
                form.val('form_edit', res.data)
            }
        })
    })
    $('body').on('submit', '#form_edit', function(e) {
        e.preventDefault()
        $.ajax({
            method: 'put',
            url: '/my/cate/info',
            data: $(this).serialize(),
            success: function(res) {
                if (res.code !== 0) {
                    return layer.msg('更新分类信息失败！')
                }
                layer.msg('更新分类信息成功！')
                layer.close(indexEdit)
                initArtList()
            }
        })
    })
    $('tbody').on('click', '#btn_del', function() {
        let id = $(this).attr('data-id')
        layer.confirm('确认删除?', { icon: 3, title: '提示' }, function(index) {
            //do something
            $.ajax({
                method: 'DELETE',
                url: '/my/cate/del?id=' + id,
                success: function(res) {
                    if (res.code !== 0) {
                        return layer.msg('分类删除失败！')
                    }
                    layer.msg('分类删除成功！')
                    layer.close(index)
                    initArtList()
                }
            })
        });
    })
})